# coding:utf-8
import requests
from jinja2 import Template

# 用例API(需根据不同用例来调整)
# ####################### 需根据不同用例来调整 #########################
CASE_API = "/api/fastrunner/run_testsuite_pk/71/"
payload = {
    "async": False,
    "config": "配置2",
    "host": "测试环境",
    "name": "京东订单2",
    "project": 7,
    "reportName": "",
    "excelTreeData": ""
}
# ######################################################################

# 邮件模板内容
TEMPLATE_FILE = "/static/fastrunner/orgin_report_template.html"

BASE_URL = "http://wetest.thinkinpower.net:8000"

print("==> begin to generate report html")

try:
    print("==> step1:get report template")
    resp = requests.get(BASE_URL + TEMPLATE_FILE)
    resp.encoding = "utf-8"
    template_content = resp.text

    print("==> step2:triger case api and get summary")
    resp = requests.post(BASE_URL + CASE_API, data=payload, auth=("test", "test123456"))
    summary = resp.json()
    if "status" in summary:
        print("==> generate report html error!")
        exit(0)
    print(f'API接口测试结果:{summary.get("success")}')  # 该打印信息，会在jenkins Text Finder 插件中用来正则匹配，改变job的构建状态。
    print("==> step3:generate report html")
    # WORKSPACE = os.getenv("WORKSPACE")
    # report_file = os.path.join(WORKSPACE,"api_report.html")
    report_file = "api_report.html"
    with open(report_file, 'w', encoding='utf-8') as fp_w:
        rendered_content = Template(
            template_content,
            extensions=["jinja2.ext.loopcontrols"]
        ).render(summary)
        fp_w.write(rendered_content)

except Exception as e:
    print(str(e))
    print("==> generate report html error!")
    exit(0)

print("==> generate report html success!")
